// This is a JavaScript file
function GoogleMapController(){ }
GoogleMapController.prototype.params = {};

$(function() {
    var markers = null;
    var latlng = new google.maps.LatLng(35.69167,139.700211),
        myOptions = {
            zoom: 16,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
    
    var map = new google.maps.Map(document.getElementById("g-map-canvas"), myOptions);
    
    $(document).on('pageshow', '#pageGMap', function(){
        PageChangeController.prototype.freeMemory();
        monaca.updateUIStyle("titlelable", "text", "グーグルマップ");
        monaca.updateUIStyle("footer", "visibility", "false");
        Util.prototype.changeSnapperElement("gmap-content", true);

        // remove all marker
        clearMarkers();
        // add new marker
        var curLocalName = GoogleMapController.prototype.params.localName;
        var dataCount = GoogleMapController.prototype.params.number;
        
        google.maps.event.trigger(map, 'resize');

        if (dataCount == 0) {
            getLatLongByCityName(curLocalName);
            return;
        }
        
        BookmarksService.prototype.loadProductbyPref(curLocalName, function(results) {
            var length = results.rows.length;
            var dataSet = [], clusters = null;
            for (var i = 0; i < length; i ++) {
                var curItem = results.rows.item(i);                
                var lat = curItem.lat,
                    lng = curItem.lng;
                // check lat, lng empty
                if (lat === '' || lng === '' || lat == -1 || lng == -1) {
                    continue;
                }
                dataSet.push(curItem);                
            }
            
            if (length == 0 || dataSet.length == 0) {
                getLatLongByCityName(curLocalName);
            } else {
                clusters = KMeansClustering.prototype.clustering(dataSet);            
                drawPin(clusters, dataSet, true);
                Util.prototype.hideSpinner();
            }
        });
        
        BookmarksService.prototype.loadProductbyDiffPref(curLocalName, function(results) {
            var length = results.rows.length;
            var dataSet = [], clusters = null;
            var preCity = '#';
            for (var i = 0; i < length; i ++) {
                var curItem = results.rows.item(i);                
                var lat = curItem.lat,
                    lng = curItem.lng;
                // check lat, lng empty
                if (lat === '' || lng === '' || lat == -1 || lng == -1) {
                    continue;
                }
                if (preCity == '#') {
                    preCity = curItem.city_name;
                } else if (preCity != curItem.city_name) {
                    preCity = curItem.city_name;                    
                    if (dataSet.length > 0) {
                        var pDataSet = cloneArray(dataSet);
                        clusters = KMeansClustering.prototype.clustering(pDataSet);            
                        drawPin(clusters, pDataSet, false);
                    }
                    dataSet = [];
                }
                dataSet.push(curItem);                
            }
            if (dataSet.length > 0) {
                clusters = KMeansClustering.prototype.clustering(dataSet);            
                drawPin(clusters, dataSet, false);
            }
        });
           
    });
    
    function cloneArray(arr) {
        var nArr = [];
        for (var i = 0, j = arr.length; i < j; i ++) {
            nArr.push(arr[i]);
        }
        return nArr;
    }
    
    function drawPin(pClusters, pDataSet, setCenter) {
        var marker,
            centrois = pClusters.centroids,
            groups = pClusters.groups;
        for (var i = 0; i < centrois.length; i ++) {
            // console.log("draw " + i + ": " + JSON.stringify(groups[i]) + ", center: (" + centrois[i].lat + ", " + centrois[i].lng + ")");
            var curLatLng = new google.maps.LatLng(centrois[i].lat, centrois[i].lng);
            marker = new google.maps.Marker({
                position:curLatLng,
                map: map,
                title: centrois[i].name,
                animation: google.maps.Animation.DROP,
                draggable: false
            });
            
            markers.push(marker);
            
            google.maps.event.addListener(marker, 'click', (function(marker, center, data) {
                return function() {                    
                    map.setCenter(marker.getPosition());
                    var items = [];
                    for (var i = 0; i < data.length; i ++) {
                        var curData = pDataSet[data[i]];
                        items.push({lat: curData.lat, lng: curData.lng});
                    }
                    // console.log("pin: " + JSON.stringify(items) + "; group: " + JSON.stringify(data));
                    var params = {'title': "ブックマーク一覧", 'fromPage': 'pageGMap', 'LatLon': items};
                    PageChangeController.prototype.changeToPage("pageBookmarkList", params);
                };
            })(marker, centrois[i], groups[i]));
            
            if (setCenter && i == 0) {
                map.setCenter(curLatLng);
            }
        }
    }
    
    // Remove all markers from map
    function clearMarkers() {
        if (markers != null) {
            for (var i = 0; i < markers.length; i++) {
                markers[i].setMap(null);
            }
        }
        // clear all items into markers
        markers = [];
    }
    
    function getListProducts(lat, lng) {
        var items = [];
        for (var i = 0; i < products.length; i ++) {
            if (products[i].lat == lat && products[i].lng == lng) {
                items.push(products[i]);
            }
        }
        return items;
    }  
    
    function getLatLongByCityName(cityName) {
        var url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + cityName +
                    '&components=administrative_area:' + cityName +
                    '|country:JP|locality:' + cityName +
                    '&sensor=false&region=jp&language=ja';             
        $.ajax({
                type: 'GET',
                url: url,
                dataType: 'json',
                success: function(result){                    
                    var center = latlng;
                    if (result.status == "OK") {
                        // geometry contains the following information:
                        // location contains the geocoded latitude,longitude value. For normal address lookups, this field is typically the most important.
                        var location = result.results[0].geometry.location;
                        if (typeof location.lat !== 'undefined' && typeof location.lng !== 'undefined') {
                            center = new google.maps.LatLng(location.lat, location.lng);
                        }
                    }
                    map.setCenter(center);
                    Util.prototype.hideSpinner();
                }, error: function(ex) {
                    map.setCenter(latlng);
                    Util.prototype.hideSpinner();
                }         
        });
    }
    
    GoogleMapController.prototype.freeMemory = function(isPageHome) {
        clearMarkers();
        markers = null;
        if (isPageHome) {
            GoogleMapController.prototype.params = null;            
        }
    };
});
